﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ContributionDeposit.CoreFrontEnd;
using Models.DataModel;
using System.Threading.Tasks;
using PagedList;
using PagedList.Mvc;
using System.Data;
using System.IO;

namespace ContributionDeposit.Controllers
{
    public class PortController : Core_FrontEnd
    {
        //
        // GET: /Port/
        public ActionResult Index(string searchtext, int? page)
        {
            CheckUserLogin = CheckLogin();
            if (CheckUserLogin == true)
            {
                int pageNum = (page ?? 1);
                var lstPort = fun_db.GetlstPort().ToList();
                ViewBag.SearchText = searchtext;
                if (!string.IsNullOrEmpty(searchtext))
                    lstPort = lstPort.Where(c => c.Name.ToUpper().Contains(searchtext.ToUpper())).ToList();
                return View(lstPort.ToPagedList(pageNum, 10));
            }
            else
                return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }

        public ActionResult AddPort()
        {
            CheckUserLogin = CheckLogin();
            if (CheckUserLogin == true)
            {
                ViewBag.lstCountryCode = new SelectList(fun_db.GetListCountry().ToList(), "CountryId", "Name");
                return View();
            }
            else
                return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }
        [HttpPost]
        public async Task<ActionResult> AddPort(Port port)
        {
            CheckUserLogin = CheckLogin();
            if (CheckUserLogin == true)
            {
                if (ModelState.IsValid)
                {
                    if (!fun_db.CheckExistPortNumber(port.PortNumber))
                    {
                        port.CreatedBy = port.ModifiedBy = fun_db.GetObjUserByUsername(Session["user"].ToString()).UserAccountID;
                        port.CreatedOn = port.ModifiedOn = DateTime.Now;
                        port.ModifiedByName = Session["user"].ToString();
                        int result = await fun_db.AddPort(port);
                        if (result == 1)
                        {
                            return RedirectToAction("Index");
                        }
                    }
                    else
                        ViewBag.ExistPortNumber = "Port number is existed";
                }
                ViewBag.lstCountryCode = new SelectList(fun_db.GetListCountry().ToList(), "CountryId", "Name");
                return View();
            }
            else
                return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }

        public ActionResult EditPort(Guid portId)
        {
            CheckUserLogin = CheckLogin();
            if (CheckUserLogin == true)
            {
                var objport = fun_db.GetObjPort(portId);
                ViewBag.lstCountryCode = new SelectList(fun_db.GetListCountry().ToList(), "CountryId", "Name");
                return View(objport);
            }
            else
                return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });

        }
        [HttpPost]
        public async Task<ActionResult> EditPort(Port port)
        {
            CheckUserLogin = CheckLogin();
            if (CheckUserLogin == true)
            {
                if (ModelState.IsValid)
                {
                    port.ModifiedBy = fun_db.GetObjUserByUsername(Session["user"].ToString()).UserAccountID;
                    port.ModifiedOn = DateTime.Now;
                    int result = await fun_db.EditPort(port);
                    return RedirectToAction("Index");
                }
                ViewBag.lstCountryCode = new SelectList(fun_db.GetListCountry().ToList(), "CountryId", "Name");
                return View();
            }
            else
                return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }
        public async Task<ActionResult> DeletePort(string view_portId)
        {
            CheckUserLogin = CheckLogin();
            if (CheckUserLogin == true)
            {
                try
                {
                    int result = -1;
                    if (!view_portId.Contains('|'))
                    {
                        Guid _GroupId = Guid.Parse(view_portId);
                        result = await fun_db.DeletePort(_GroupId);
                    }
                    else
                    {
                        string[] arrId = view_portId.Split('|');
                        for (int i = 0; i < arrId.Length - 1; i++)
                        {
                            Guid _GroupId = Guid.Parse(arrId[i]);
                            result = await fun_db.DeletePort(_GroupId);
                        }
                    }
                    return Json(result);
                }
                catch
                {

                }
                return Json("-1", JsonRequestBehavior.AllowGet);
            }
            else
                return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }

        public JsonResult SearchPort(string view_keyword)
        {
            try
            {
                var lstPort = fun_db.GetlstPortbyName(view_keyword).ToList();
                return Json(lstPort);
            }
            catch
            {

            }
            return Json("-1", JsonRequestBehavior.AllowGet);
        }

        public ActionResult ExportPort()
        {
            CheckUserLogin = CheckLogin();
            if (CheckUserLogin == true)
            {
                var fileName = string.Format("{0} {1}.xlsx", ControllerContext.RouteData.Values["controller"].ToString(), DateTime.Now.ToString("yyyyMMdd HHmmss"));

                string filepath = AppDomain.CurrentDomain.BaseDirectory + "App_Data/ExcelFiles/" + fileName;
                DataTable dt = Utilities.Utility.ConvertToDataTable(fun_db.GetlstPort().ToList());

                Utilities.Utility.WriteDataTableToExcel(dt, Path.GetFileNameWithoutExtension(fileName), filepath, "Details");
                byte[] filedata = System.IO.File.ReadAllBytes(filepath);
                string contentType = MimeMapping.GetMimeMapping(filepath);

                var cd = new System.Net.Mime.ContentDisposition
                {
                    FileName = fileName,
                    Inline = true,
                };

                Response.AppendHeader("Content-Disposition", cd.ToString());
                System.IO.File.Delete(filepath);
                return File(filedata, contentType);
            }
            else
                return RedirectToAction("Login", "Account", new { ReturnUrl = Request.Url.AbsoluteUri });
        }
    }
}